package com.halflife.nettyio;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    public static void main(String[] args)throws Exception {
        EchoServer server = new EchoServer();
        server.start();
    }

    public void start() throws Exception{
        NioEventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group).channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(9090))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on "
                + channelFuture.channel().localAddress());
        channelFuture.channel().closeFuture().sync();
        group.shutdownGracefully().sync();
    }
}
